package dao;


import entity.Ties;

import java.sql.*;

import utils.DBUtil;
import utils.JwtUtil;

import java.util.ArrayList;
import java.util.List;

public class TiesDao {
    public List<Ties> findAllNew(){
        List <Ties>a = new ArrayList();
        String sql=" select Uname,Upic,Text\n" +
                "from Postinfo a , Userinfo b,Content c where a.Ucode = b.Ucode and a.Pid=c.Pid order by a.Utime desc ";
        Connection conn= DBUtil.getConnection();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs=ps.executeQuery();
            while (rs.next()){
                String name=rs.getString(1);
                String Pname=rs.getString(1);
                String content=rs.getString(1);
                Ties b=new Ties(name,Pname,content);
                a.add(b);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return a;
    }
    public int addTie(int text,String texts){
        String sql="insert into postinfo(Ucode,Pgood,Prelay,ptype)  values(?,0,0,1)";
        int num=0;
        Connection conn=DBUtil.getConnection();
        PreparedStatement ps=null;
        try  {
             ps = conn.prepareStatement(sql);
            ps.setInt(1,text);
             num= ps.executeUpdate();
            System.out.println(num);
             DBUtil.close( conn,  ps, null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        int pid= findFinaly(text);
        addTieInfo(pid,texts);




        return num;
    }
    public void addTieInfo(int text,String texts){
        String sql="insert into Content values(?,?,?)";
        System.out.println(text);
        Connection conn=DBUtil.getConnection();
        PreparedStatement ps=null;
        try  {
             ps = conn.prepareStatement(sql);
            ps.setString(1,texts);
            ps.setString(2,"");
            ps.setInt(3,text);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(conn,ps,null);

        }

    }
        public int findFinaly(int Ucode){
        int pid=0;
        String sql="select  top 1 pid from Postinfo where Ucode=? order by pid desc";
        Connection conn=DBUtil.getConnection();
            PreparedStatement ps=null;
            ResultSet rs=null;
            try {
                 ps=conn.prepareStatement(sql);
                 ps.setInt(1,Ucode);
               rs=  ps.executeQuery();
               if (rs.next()){
                   pid=rs.getInt(1);
               }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                DBUtil.close(conn,ps,rs);
            }

            return pid;
        }
}
